import { MissTargetError } from './../filter/miss.filter';
import {
  App,
  Body,
  Controller,
  Get,
  Inject,
  Param,
  Post,
  Del,
  Provide,
  Put,
  Scope,
  ScopeEnum,
  Query,
} from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
import { Person } from '../interface';
import { Mockdb, BillCodeGenerator } from '../service/mockdb.service';
import { Context } from '@midwayjs/koa';

@Controller('/funny')
@Provide()
@Scope(ScopeEnum.Singleton)
export class FunnyController {
  @Inject()
  private mockdb: Mockdb;
  @Inject()
  private billCodeGenerator: BillCodeGenerator;
  @App()
  app: koa.Application;
  //   async onReady() {
  //     this.human = ;
  //   }
  @Inject()
  ctx: Context;

  @Post('/insert')
  public async insert(@Body() person: Person) {
    console.log(person);
    const p = {
      id: 0,
      name: person.name,
      age: person.age,
    };
    // p.id = this.mockdb.personDB.length;
    p.id = this.billCodeGenerator.generate();
    this.mockdb.personDB.push(p);
    console.log(this.mockdb.personDB);
    return p;
  }
  @Post('/oldStyleInsert')
  public async oldStyleInsert(
    @Query('name') name: string,
    @Query('age') age: number
  ) {
    console.log('旧式数据', name, age);
    const p = {
      id: 0,
      name: name,
      age: age,
    };
    // p.id = this.mockdb.personDB.length;
    p.id = this.billCodeGenerator.generate();
    this.mockdb.personDB.push(p);
    console.log(this.mockdb.personDB);
    return p;
  }
  @Get('/find/:id')
  public async findById(@Param('id') id: number) {
    console.log('path id ', id);
    return this.mockdb.personDB.find(x => x.id === id) || {};
  }
  @Get('/browse')
  public async browse() {
    return this.mockdb.personDB;
  }
  @Put('/modify')
  public async modify(@Body() person: Person) {
    const p: Person = this.mockdb.personDB.find(x => x.id === person.id);
    if (p) {
      p.name = person.name;
      p.age = person.age;
      return p;
    } else {
      throw new MissTargetError('待修改的数据不存在 ' + person.id);
    }
  }
  @Del('/remove/:id')
  public async removeById(@Param('id') id: number) {
    const t = this.mockdb.personDB.findIndex(x => x.id === id);
    if (t < 0) {
      throw new MissTargetError('待删除的数据不存在 ' + id);
    } else {
      this.mockdb.personDB.splice(t, 1);
      return true;
    }
  }
  @Get('/browsePage')
  public async browsePage() {
    // let db = this.mockdb.personDB;
    const queryFromDB = {
      foo: 'bar',
      content: [
        { name: 'foolish', age: 11 },
        { name: 'like', age: 12 },
      ],
    };
    await this.ctx.render('person.html', queryFromDB);
  }
  @Get('/test')
  public async render() {
    const queryFromDB = { user: 'midway' };
    await this.ctx.render('test.nj', queryFromDB);
  }
}
